package com.bitBusy.manageyourriches.activity;

import java.util.LinkedHashMap;
import java.util.Map.Entry;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bitBusy.manageyourriches.R;
import com.bitBusy.manageyourriches.database.contactClasses.ExpenseDetails;
import com.bitBusy.manageyourriches.database.managers.DatabaseInteractor;
import com.bitBusy.manageyourriches.database.managers.DateTimeManager;
import com.bitBusy.manageyourriches.utilityClasses.checkers.NullChecker;
import com.bitBusy.manageyourriches.utilityClasses.navigation.ActionBarChoice;
import com.bitBusy.manageyourriches.utilityClasses.pickers.DateChangeListener;
import com.bitBusy.manageyourriches.utilityClasses.pickers.TimeChangeListener;
import com.bitBusy.manageyourriches.utilityClasses.setters.AddAddNewToMap;

public class EditExpenseRecordActivity extends FragmentActivity implements DateChangeListener, TimeChangeListener{

	/** String to be displayed when record saved*/
	private static final String RECORDSAVEDPROMPT = "Expense record saved!";

	/**DB Interactor*/
	private DatabaseInteractor myDBInteractor;
	
	/** date chosen*/
	private int myDateChosen;
	
	/** time chosen*/
	private String myTimeChosen;

	/** amount chosen*/
	private String myAmountChosen;

	/** Category chosen*/
	private String myCategoryChosen;
	

	/** Initial Category chosen*/
	private String myInitialCategoryChosen;

	/**Subcategory chosen*/
	private String mySubcategoryChosen;
	
	/**Initial Subcategory chosen*/
	private String myInitialSubcategoryChosen;
	
	/**Payment method chosen*/
	private String myPaymentMethodChosen;
	
	/** note chosen*/
	private String myNoteChosen;

	/**Previous chosen view */
	private View myPreviousCategoryView;

	/**Previous chosen view */
	private View myPreviousSubcategoryView;
	
	/**Previous chosen view */
	private View myPreviousPaymentView;

	/** Previous record*/
	private ExpenseDetails myPreviousExpenseRecord;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myDBInteractor = new DatabaseInteractor(this);
		setContentView(R.layout.activity_edit_expense_record);
		getIntentValues();
		setDate();
		setTime();
		setAmount();
		setCategories();
		setSubcategories();
		setPaymentMethods();
		setNote();
		
	}


	/** Method to get intent values*/
	private void getIntentValues()
	{
		myDateChosen = getIntent().getIntExtra(ViewExpensesActivity.DATE_CHOSEN, 0);
		myTimeChosen = getIntent().getStringExtra(ViewExpensesActivity.TIME_CHOSEN);
		myAmountChosen = getIntent().getStringExtra(ViewExpensesActivity.AMOUNT_CHOSEN);
		myInitialCategoryChosen = getIntent().getStringExtra(ViewExpensesActivity.CATEGORY_CHOSEN);
		myCategoryChosen = myInitialCategoryChosen;
		myInitialSubcategoryChosen = getIntent().getStringExtra(ViewExpensesActivity.SUBCATEGORY_CHOSEN);
		mySubcategoryChosen = myInitialSubcategoryChosen;
		myPaymentMethodChosen = getIntent().getStringExtra(ViewExpensesActivity.PAYMENTMETHOD_CHOSEN);
		myNoteChosen = getIntent().getStringExtra(ViewExpensesActivity.NOTE_CHOSEN);
		myPreviousExpenseRecord = new ExpenseDetails(DateTimeManager.getDateTime(myDateChosen, myTimeChosen),
				myPaymentMethodChosen, Double.parseDouble(myAmountChosen), myNoteChosen);
		
	}
	
	/** sets date on button*/
	private void setDate()
	{
		Button dateButton =(Button)findViewById(R.id.edit_dateButton);
		dateButton.setText(DateTimeManager.parseForUserDate(myDateChosen));
	}
	
	/** gets date on button*/
	private int getDate()
	{
		Button dateButton =(Button)findViewById(R.id.edit_dateButton);
		return DateTimeManager.parseForDBDate(dateButton.getText().toString());
	}
	
	/** sets time on button*/
	private void setTime()
	{
		Button timeButton =(Button)findViewById(R.id.edit_timeButton);
		timeButton.setText(myTimeChosen);
	}
	
	/** gets time on button*/
	private String getTime()
	{
		Button timeButton =(Button)findViewById(R.id.edit_timeButton);
		return timeButton.getText().toString();
	}
	
	/** sets amount*/
	private void setAmount()
	{
		EditText amtText = (EditText) findViewById(R.id.edit_amtText);
		amtText.setText(myAmountChosen);
	}

	/** gets amount*/
	private String getAmount()
	{
		EditText amtText = (EditText) findViewById(R.id.edit_amtText);
		return amtText.getText().toString();
	}

	/** Method to set categories*/
	private void setCategories()
	{
		if (myDBInteractor != null)
		{
			LinkedHashMap<String, Integer> categories = AddAddNewToMap.getModifiedMap(myDBInteractor.getAllCategoriesAndImages(), HomeActivity.CATEGORYADDNEWIMG);
			if (categories != null)
			{
				
				 LinearLayout rootLayout = (LinearLayout) findViewById(R.id.edit_categoryLayout);
				 rootLayout.removeAllViews();
				 LayoutInflater inflater = (LayoutInflater) this
			    			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			    		for(Entry<String, Integer> category: categories.entrySet())
		    			{
		    				 View view = new View(this);
		    			     view = inflater.inflate(R.layout.menu_button_home, null);
		    			     
		    			     TextView textView = (TextView) view
		    	    					.findViewById(R.id.grid_item_text);
		    	    			ImageView imageView = (ImageView) view
		    	    					.findViewById(R.id.grid_item_image);
		    	    		    
		    	    			setViewValues(rootLayout, textView, imageView, category, view, true, false, false);
		    					rootLayout.addView(view);
		    					
		    			}
		     }   			
		}
		
		
	}
	
	/** Method to set subcategories*/
	private void setSubcategories()
	{
		if (myDBInteractor != null)
		{
			LinkedHashMap<String, Integer> subcategories = 
					AddAddNewToMap.getModifiedMap(myDBInteractor.getSubcategories(myCategoryChosen), HomeActivity.CATEGORYADDNEWIMG);
			if (subcategories != null)
			{
				
				 LinearLayout rootLayout = (LinearLayout) findViewById(R.id.edit_subcategoryLayout);
				 rootLayout.removeAllViews();
				 LayoutInflater inflater = (LayoutInflater) this
			    			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				 boolean firstEntry = true;
			    		for(Entry<String, Integer> category: subcategories.entrySet())
		    			{
		    				 View view = new View(this);
		    			     view = inflater.inflate(R.layout.menu_button_home, null);
		    			     
		    			     TextView textView = (TextView) view
		    	    					.findViewById(R.id.grid_item_text);
		    	    			ImageView imageView = (ImageView) view
		    	    					.findViewById(R.id.grid_item_image);
		    	    		    
		    	    			if (firstEntry)
		    	    			{
		    	    				firstEntry = false;
		    	    			}
		    	    			setViewValues(rootLayout, textView, imageView, category, view, false, true, false);
		    					rootLayout.addView(view);
		    					
		    			}
		     }   			
		}
		
		
	}
	
	/** Method to set payment methods*/
	private void setPaymentMethods()
	{
		if (myDBInteractor != null)
		{
			LinkedHashMap<String, Integer> methods = 
					AddAddNewToMap.getModifiedMap(myDBInteractor.getAllPaymentInfo(), ConfirmActivity.PAYMENTMETHODPICID);
			if (methods != null)
			{
				
				 LinearLayout rootLayout = (LinearLayout) findViewById(R.id.edit_paymentInfoLayout);
				 rootLayout.removeAllViews();
				 LayoutInflater inflater = (LayoutInflater) this
			    			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			    		for(Entry<String, Integer> category: methods.entrySet())
		    			{
		    				 View view = new View(this);
		    			     view = inflater.inflate(R.layout.menu_button_home, null);
		    			     
		    			     TextView textView = (TextView) view
		    	    					.findViewById(R.id.grid_item_text);
		    	    			ImageView imageView = (ImageView) view
		    	    					.findViewById(R.id.grid_item_image);
		    	    		    
		    	    			setViewValues(rootLayout, textView, imageView, category, view, false, false, true);
		    					rootLayout.addView(view);
		    					
		    			}
		     }   			
		}
		
		
	}
	
	
	/**Method to set values of the payment method views
	 * @param the text view
	 * @paaram the image view
	 * @param the map entry
	 * @param the compound view
	 */
	private void setViewValues(final LinearLayout the_parentLayout, 
			TextView the_textView, ImageView the_imageView, Entry<String, Integer> the_entry, View the_view, boolean the_isCategory, boolean the_isSubcategory,
													boolean the_isPayment)
	{
		if (!NullChecker.checkForNullValues(new Object[]{the_textView, the_imageView, the_entry, the_view}))
		{
			the_textView.setText(the_entry.getKey());
			the_imageView.setImageResource(the_entry.getValue());
			the_view.setClickable(true);
			the_view.setPadding(ConfirmActivity.DEFAULTPADDING, ConfirmActivity.DEFAULTPADDING, ConfirmActivity.DEFAULTPADDING, ConfirmActivity.DEFAULTPADDING);
			the_view.setFocusable(true); 
			if (the_isCategory && myCategoryChosen != null && myCategoryChosen.equals(the_entry.getKey()))
			{
				the_view.setBackground(getResources().getDrawable(R.drawable.selectedvalue_click_state_colors));
				myPreviousCategoryView = the_view;
				setInFocus(the_view, (HorizontalScrollView)findViewById(R.id.edit_categoryScroll));
			}
			else if (the_isSubcategory && (mySubcategoryChosen != null && mySubcategoryChosen.equals(the_entry.getKey()) ||
					mySubcategoryChosen == null))
			{
				the_view.setBackground(getResources().getDrawable(R.drawable.selectedvalue_click_state_colors));
				myPreviousSubcategoryView = the_view;
				if (mySubcategoryChosen == null)
				{
					mySubcategoryChosen = the_entry.getKey();
				}
				setInFocus(the_view, (HorizontalScrollView)findViewById(R.id.edit_subcategoryScroll));

			}
			else if (the_isPayment && ((myPaymentMethodChosen != null && myPaymentMethodChosen.equals(the_entry.getKey()) ||
										myPaymentMethodChosen == null)))
			{
				the_view.setBackground(getResources().getDrawable(R.drawable.selectedvalue_click_state_colors));
				myPreviousPaymentView = the_view;
				if (myPaymentMethodChosen == null)
				{
					myPaymentMethodChosen = the_entry.getKey();
				}
				setInFocus(the_view, (HorizontalScrollView)findViewById(R.id.edit_paymentInfoScroll));

			}
			else
			{
				the_view.setBackground(getResources().getDrawable(R.drawable.click_state_colors));
			}
			
			setListeners(the_view,the_isCategory, the_isSubcategory, the_isPayment);
		}
	}
	
	/** sets view in focus
	 * @param the view
	 * @param the horizontal scroll view
	 */
	private void setInFocus(final View the_view, final HorizontalScrollView the_horizontalScroll)
	{
		if (the_view != null)
		{
			
			 new Handler().post(new Runnable() {
			        @Override
			        public void run() {
			            int vLeft = the_view.getLeft();
			            int vRight = the_view.getRight();
			            int width = the_view.getWidth();
			            the_horizontalScroll.smoothScrollTo(((vLeft + vRight) / 2) - (width), 0);
			        }
			    });		}
		
	}

	/**
	 * Listeners for view
	 * @param the_view
	 * @param the_isCategory
	 * @param the_isSubcategory
	 * @param the_isPayment
	 */
	private void setListeners(View the_view, boolean the_isCategory,
			boolean the_isSubcategory, boolean the_isPayment) {
		if (the_view != null)
		{
			if (the_isCategory)
			{
				the_view.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View the_view) {
						if (the_view != null)
						{
							TextView textView = (TextView) the_view
		    					.findViewById(R.id.grid_item_text);
							String choice = textView.getText().toString();
							if(AddAddNewToMap.ADDNEW.equals(choice))       		
				        	{
				        		//addNewPaymentMethod();
				        		
				        	}
				        	else
				        	{
				        		the_view.setBackground(getResources().getDrawable(R.drawable.selectedvalue_click_state_colors));
				        		View previous = myPreviousCategoryView;
				        		if (previous != null)
				        		{
				        			previous.setBackground(getResources().getDrawable(R.drawable.click_state_colors));
				        		}								
				        	}
			        		myPreviousCategoryView = the_view;
			        		myCategoryChosen = choice;
			        		mySubcategoryChosen = null;
			        		myPaymentMethodChosen = ConfirmActivity.DEFAULTPAYMENTMETHOD;
							setSubcategories();
						
						}
					}
				});
			}
			
			else if (the_isSubcategory)
			{
				the_view.setOnClickListener(new View.OnClickListener(){
					
					@Override
					public void onClick(View the_view) {
						if (the_view != null)
						{
							TextView textView = (TextView) the_view
		    					.findViewById(R.id.grid_item_text);
							String choice = textView.getText().toString();
							if(AddAddNewToMap.ADDNEW.equals(choice))       		
				        	{
				        		//addNewPaymentMethod();
				        		
				        	}
				        	else
				        	{
				        		the_view.setBackground(getResources().getDrawable(R.drawable.selectedvalue_click_state_colors));
				        		View previous = myPreviousSubcategoryView;
				        		if (previous != null)
				        		{
				        			previous.setBackground(getResources().getDrawable(R.drawable.click_state_colors));
				        		}								
				        	}
							myPreviousSubcategoryView = the_view;
			        		mySubcategoryChosen = choice;
						
						}
					}
				});
			}
			else if (the_isPayment)
			{
				the_view.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View the_view) {
					if (the_view != null)
					{
						TextView textView = (TextView) the_view
	    					.findViewById(R.id.grid_item_text);
						String choice = textView.getText().toString();
						if(AddAddNewToMap.ADDNEW.equals(choice))       		
			        	{
			        		//addNewPaymentMethod();
			        		
			        	}
			        	else
			        	{
			        		the_view.setBackground(getResources().getDrawable(R.drawable.selectedvalue_click_state_colors));
			        		View previous = myPreviousPaymentView;
			        		{
			        			previous.setBackground(getResources().getDrawable(R.drawable.click_state_colors));
			        		}								
			        	}
						myPreviousPaymentView = the_view;
		        		myPaymentMethodChosen = choice;
					
					}
				}
			});
	
			}
		}
	}
	
	/** sets note*/
	private void setNote()
	{
		EditText noteText = (EditText) findViewById(R.id.edit_noteText);
		noteText.setText(myNoteChosen);
	}
	
	/**saves record
	 * @param the view
	 */
	public void save(View the_view)
	{
		if (the_view != null)
		{
			ExpenseDetails expense = new ExpenseDetails(DateTimeManager.getDateTime(getDate(), getTime()),
						myPaymentMethodChosen, Double.parseDouble(getAmount()), myNoteChosen);
			if ((!myInitialCategoryChosen.equals(myCategoryChosen) || !myInitialSubcategoryChosen.equals(mySubcategoryChosen) || 
					(myPreviousExpenseRecord != null &&!myPreviousExpenseRecord.isEqual(expense))) && 
					myDBInteractor.deleteRecord(myInitialCategoryChosen, myInitialSubcategoryChosen,myPreviousExpenseRecord) && 
				myDBInteractor.addExpenseDetails(mySubcategoryChosen, myCategoryChosen,expense))
			{
				Toast.makeText(getApplicationContext(), 
						RECORDSAVEDPROMPT, Toast.LENGTH_LONG).show();							
			}
			
			goBack();
		}
	}
	
	/** goes back to view expenses activity*/
	private void goBack()
	{
		Intent intent = new Intent(this, ViewExpensesActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		
	}
	
	/** change time
	 * @param the view
	 */
	public void changeTime(View the_view)
	{
		if (the_view != null)
		{
			DateTimeManager.changeTime(this, this, (Button) findViewById(R.id.edit_timeButton));
		}
	}
	
	/** change date
	 * @param the view
	 */
	public void changeDate(View the_view)
	{
		if (the_view != null)
		{
			DateTimeManager.changeDate(this, this, (Button) findViewById(R.id.edit_dateButton));
		}
	}


	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.utilityClasses.pickers.TimeChangeListener#timeHasChanged(android.widget.TextView)
	 */
	@Override
	public void timeHasChanged(TextView the_view) {
		// do nothing		
		
	}


	/* (non-Javadoc)
	 * @see com.bitBusy.manageyourriches.utilityClasses.pickers.DateChangeListener#dateHasChanged(android.widget.TextView)
	 */
	@Override
	public void dateHasChanged(TextView the_view) {
		// do nothing		
	}
	
	 @Override
	  public boolean onCreateOptionsMenu(Menu the_menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.actionbar_menu, the_menu);
	    return true;
	  }
	  
	 @Override
	  public boolean onOptionsItemSelected(MenuItem the_item) {
	    ActionBarChoice.choiceMade(this, the_item.getItemId());

	    return true;
	  }
	
	
		
}
